package com.scetoop.bank;

import com.scetoop.banking.domain.OverdraftException;

public class CheckingAccount extends  Account{
//    private double overdraftProtection;
    private SavingAccount protectedBy = null;
    public CheckingAccount(double balance){
        super(balance);
//        this.overdraftProtection = 0;
    }
    public CheckingAccount(double balance, SavingAccount protect){
        super(balance);
//        this.overdraftProtection = protect;
        this.protectedBy = protect;
    }
//    public boolean withdraw(double amt){
//        if (amt > 0 ){
//            if (balance >= amt){
//                balance -= amt;
//                return true;
//            }else if (protectedBy != null){
//                double overdraftNeeded = amt - balance;
//                if (protectedBy.getBalance() >= overdraftNeeded){
//                    protectedBy.withdraw(overdraftNeeded);
////                    balance -= amt;
//                    balance = 0;
//                    return true;
//                }
//            }
//        }
//        return false;
//    }
public void withdraw(double amt) throws OverdraftException {
    if (amt > 0) {
        if (balance >= amt) {
            balance -= amt;
        } else {
            if (protectedBy == null) {
                throw new OverdraftException("no overdraft protection", amt - balance);
            } else {
                double overdraftNeeded = amt - balance;
                if (protectedBy.getBalance() >= overdraftNeeded) {
                    try {
                        protectedBy.withdraw(overdraftNeeded);
                        balance = 0;
                    } catch (OverdraftException e) {
                        throw new OverdraftException("Insufficient funds for overdraft protection", overdraftNeeded);
                    }
                } else {
                    throw new OverdraftException("Insufficient funds for overdraft protection", overdraftNeeded);
                }
            }
        }
    }
}
}
